package ldh.im.fxbase.service;

import ldh.im.fxbase.dao.ImMessageDao;
import ldh.im.fxbase.dao.ImSessionDao;
import ldh.im.fxbase.data.pojo.ImHotMessageTotal;
import ldh.im.fxbase.data.pojo.ImSession;
import ldh.im.fxbase.util.ImHotMessageSingleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.List;

public class CheckHotMessageTotalService {

    private static final int SESSION_MAX_SIZE = 1000;
    private static final Logger LOGGER = LoggerFactory.getLogger(CheckHotMessageTotalService.class);

    public void checkHotMessageTotal(String userId, LocalDateTime startDate) {
        LOGGER.info("begin check hot message total");
        try {
            ImMessageDao messageDao = new ImMessageDao();
            ImSessionDao sessionDao = new ImSessionDao();
            List<ImHotMessageTotal> hotMessages = messageDao.getHotMessageTotal(userId, startDate);
            for (ImHotMessageTotal hotMessageTotal : hotMessages) {
                if (hotMessageTotal.getTotal() >= 0) {
                    ImHotMessageSingleton.getInstance().setHotMessage(hotMessageTotal.getSessionId(), hotMessageTotal.getTotal());
                }
            }
            List<ImSession> sessions = sessionDao.getByUserIdAndTimeAndSize(userId, startDate, 0, SESSION_MAX_SIZE);
            for (ImSession session : sessions) {
                boolean isHave = false;
                for (ImHotMessageTotal hotMessage : hotMessages) {
                    if (hotMessage.getSessionId().equals(session.getId())) {
                        isHave = true;
                        if (hotMessage.getTotal() == session.getHotMessageTotal().intValue()) {
                            LOGGER.info("session hot message total, sessionId: {}, hotMessageTotal: {}", session.getId(), hotMessage.getTotal());
                            sessionDao.setHotMessageNum(session.getId(), hotMessage.getTotal());
                            continue;
                        }
                    }
                }
                if (!isHave&& session.getHotMessageTotal() > 0) {
                    LOGGER.info("session hot message total 0, sessionId: {}", session.getId());
                    sessionDao.setHotMessageNum(session.getId(), 0);

                    ImHotMessageSingleton.getInstance().setHotMessage(session.getId(), 0);
                }
            }

        } catch (Exception e) {
            LOGGER.error("热点消息处理失败， error: {}", e);
        }
    }
}
